<template>
  <div class="diskInfoWrap" v-loading="loadingTime">
    <div class="shareHeadClass">
      <p class="colCLas"></p>
      <p class="info">授信额度信息</p>
    </div>

    <el-button
        type="primary"
        size="small"
        @click="getLeqiCreditLimitInfo"
        icon="el-icon-upload"
        style="margin: 4px 0"
    >
      查询授信额度信息
    </el-button>
    <el-button
        type="primary"
        @click="updatePeriod"
        size="small"
        icon="el-icon-upload"
        style="margin: 0 4px"

    >
      调整授信额度有效期
    </el-button>
    <el-button type="primary" icon="el-icon-refresh" style="margin-left: 0px" size="small" @click="getList(true)">刷新</el-button>

    <tableList
        :data="listDetails"
        border
        maxHeight="200"
        :loading="loading"
        :pageNumber="pages.current"
        :pageSize="pages.size"
        :total="pages.total"
        :keySet="keySet2"
        :tableData="listDetails"
    >
      <template #bysxed="{row}">
        {{ (+row.bysxed).toLocaleString('en-US', { minimumFractionDigits: 2 })}}
      </template>
      <template #kysyed="{row}">
        {{ (+row.kysyed).toLocaleString('en-US', { minimumFractionDigits: 2 })}}
      </template>
      <template #yxzed="{row}">
        {{ (+row.yxzed).toLocaleString('en-US', { minimumFractionDigits: 2 })}}
      </template>
      <template #yxzwsyed="{row}">
        {{ (+row.yxzwsyed).toLocaleString('en-US', { minimumFractionDigits: 2 })}}
      </template>
  </tableList>

    <div class="shareHeadClass" style="margin-top: 4px;">
      <p class="colCLas"></p>
      <p class="info">下载/回退授信额度</p>
    </div>
    <div
        class="creditContent"
    >
      <div>

      </div>
      <el-form
          :inline="true"
          :model="searchParams"
          style="width: 100%"
          size="small"
          :rules="rules"
          ref="formRef"
      >
        <el-form-item>
          <el-radio-group v-model="radio" @change="changeType()">
            <el-radio :label="1">下载</el-radio>
            <el-radio :label="2">退回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="申请额度" style="max-width: 240px">
          <el-input-number
              style="width: 160px"
              v-model="searchParams.input1"
              controls-position="right"
              :min="0.01"
              :max="99999999.99"
              :precision="2"
              placeholder="请输入申请额度"
          ></el-input-number>
        </el-form-item>

        <el-form-item
            label="审批人:"
            style="max-width: 340px"
            prop="select1"
        >
          <el-select
              style="width: 160px"
              v-model="searchParams.select1"
              placeholder="请选择"
          >
            <el-option
                v-for="option in options"
                :key="option.userCode"
                :label="option.fullName"
                :value="option.userCode"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <div style="margin-bottom: 6px">事项说明：（限制录入500字）</div>
    <el-input
        type="textarea"
        placeholder="请输入"
        v-model="textarea"
        maxlength="500"
        show-word-limit
        :rows="4"
        resize="none"
    ></el-input>
    <div style="margin-top: 8px; display: flex; justify-content: center">
      <el-button type="primary" @click="applyFn" :disabled="applyButtonDisabled">申请</el-button>
    </div>

<!--    这个模块不知道咋用的-->
    <vxe-modal v-model="validDialogShow" :position="{top: 300}">
      <template v-slot>
        <div v-if="!validDialogForm.error">
          <div>调整成功！</div>
          <div>当前授信额度属期：{{ validDialogForm.sq }}</div>
          <div>授信额度使用区间：{{ validDialogForm.sxed }}</div>
          <!-- <div>当前授信额度属期：{{ validDialogForm.sq }}</div>
          <div>授信额度使用区间：{{ validDialogForm.syqjq }} - {{ validDialogForm.syqjz }}</div> -->
        </div>
        <div v-else>
          <div>调整失败！</div>
          <div>失败原因：接口调用失败！</div>
        </div>
      </template>
    </vxe-modal>
  </div>
</template>

<script>
import mixinTable from '@/mixin/mtable.js'
import tableList from '@/components/tableList/index.vue'
import {getFlowData, saveOrSubmit} from '@/api/businessFlow.js'
import {addInfo, updateDate, getInfo} from "@/api/creditLimit.js";

export default {
  name: 'creditLimit',
  mixins: [mixinTable],
  data() {
    return {
      loading: false,
      currentRow: {
        sq: ''
      },
      findType: 0,
      loadingTime: false,

      validDialogForm: {
        syqjq: 0,
        syqjz: 0,
        sq:'',
        sxed:'',
        error:'',
      },
      validDialogShow: false,


      radio: 1,
      textarea: '',

      listDetails: [],
      keySet2: [
        {
          label: '暂停授信标志',
          englishName: 'ztsxbz',
        },
        {
          label: '本月授信额度',
          englishName: 'bysxed',
          isSlot: true,
          slotName: 'bysxed'
        },
        {
          label: '可用剩余额度',
          englishName: 'kysyed',
          isSlot: true,
          slotName: 'kysyed'
        },
        {
          label: '已下载额度',
          englishName: 'yxzed',
          isSlot: true,
          slotName: 'yxzed'
        },
        {
          label: '已下载未使用额度',
          englishName: 'yxzwsyed',
          isSlot: true,
          slotName: 'yxzwsyed'
        },
        {
          label: '属期',
          englishName: 'sq',
        },
        {
          label: '授信额度使用区间起',
                    width: 'labelWidth',
          englishName: 'syqjq',
        },
        {
          label: '授信额度使用区间止',
          englishName: 'syqjz',
                              width: 'labelWidth',
        },
      ],
      options: [],
      busType: "FLOW_XZSXED",
      busId:'',
      createTime:'',
      rules: {
        select1: [
          {
            required: true,
            message: '请选择审批人',
            trigger: 'change',
          },
        ],
        input1: [
          {
            required: true,
            message: '请输入申请额度',
            trigger: 'change',
          },
        ],
      },
      applyButtonDisabled: false,
    }
  },
  methods: {
    // 申请按钮，这个应该是在页面参数校验成功后再调用接口，但是目前是直接调用接口了，得改 TODO
    applyFn() {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) {
          this.applyButtonDisabled = false;
          return;
        }
        this.applyButtonDisabled = true; // 按钮置灰不可用
        let {data, code, message} = await saveOrSubmit(
            {
              busType: this.busType,
              busId: this.busId,
              approvalUser: this.searchParams.select1,
              submit: true,
              createTime: this.createTime,
              description: this.textarea,
              busData: JSON.stringify({applyLimit:this.searchParams.input1})
            },
        )
        if (code == 200) {
          await this.getList()
          await this.getApprovalUserList()
          // this.busType = "";
          this.searchParams.input1 = "";
          this.textarea = ""
          let type = this.radio === 1 ? "下载" : "退回";
          this.$message({
            message: '发起'+type+'授信额度申请成功！',
            type: "success"
          });
        } else {
          this.applyButtonDisabled = false;
        }
        this.applyButtonDisabled = false;
      })
    },

    // 本地存储授信额度查询
    async getList(loading) {
      this.loading = true
      let {data, code, message} = await getInfo(
          {}
      )
      if (code == 200) {
        this.listDetails = [data].map(item=>{
          return {
            ...item
          }
        })
        this.pages.total = data.total
        this.pages.current = data.current
        this.pages.size = data.size
        if(loading){
          this.$message.success(message || data)

        }
      }
      this.loading = false
    },
    // 调用乐企接口，查询授信额度信息
    getLeqiCreditLimitInfo() {
      this.$alert('是否调用接口获取授信额度信息？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        showCancelButton: true,
        type: 'warning',
      })
          .then(async () => {
            let {data, code, message} = await addInfo(
                {},
            )
            if (code == 200) {
              await this.getList()
            }
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消',
            })
          })
    },
    // 调整授信额度有效期按钮
    updatePeriod() {
      this.$alert('是否调用接口调整授信额度有效期？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        showCancelButton: true,
        type: 'warning',
      })
          .then(async () => {
            this.loadingTime = true
            let {data, code, message} = await updateDate(
                {
                  sxedsq: this.currentRow.sq || '',
                }
            )
            if (code == 200) {
              this.loadingTime = false;
              this.validDialogShow = true;
              let arr = data.split("，");
              this.validDialogForm = {
                message,
                ...data,
                sq: arr[0],
                sxed: arr[1],
              };
              await this.getList()
            } else {
              this.validDialogShow = true;
              this.validDialogForm = {
                error: 1,
                // ...data
              };

            }
            this.loadingTime = false
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消',
            })
          })
    },

    // 获取审批人列表
    async getApprovalUserList() {
      let {data, code, message} = await getFlowData({
        busType: this.busType
      });
      if (code == 200) {
        this.options = data.approvalUserList;  // 更新options数组
        if(Array.isArray(this.options)&&this.options.length){
          this.searchParams.select1 = this.options[0].userCode
        }
        this.busId = data.busId;
        this.createTime = data.createTime;
      }
    },
    changeType() {
      this.busType = this.radio === 1 ? "FLOW_XZSXED" : "FLOW_THSXED";
      this.applyButtonDisabled = false;
      this.getApprovalUserList();
    }
  },
  created() {
    this.getList()
    this.getApprovalUserList()
  },
  components: {
    tableList,
  },
}
</script>

<style lang="scss" scoped>
@import '@/style/variables.scss';

.diskInfoWrap {
  box-sizing: border-box;
  // padding: 10px;
  .shareHeadClass {
    display: flex;
    height: 18px;
    align-items: center;
    margin-bottom: 4px;

    .colCLas {
      width: 4px;
      height: 100%;
      background-color: $allBg;
      margin-right: 12px;
    }

    .info {
      height: 100%;
      display: flex;
      align-items: center;
    }
  }

  .creditContent {
    margin-bottom: 10px;

    :deep .el-form-item--small.el-form-item {
      margin-bottom: 0;
    }
  }
}
</style>
